<template>
  <div>
    <h2 v-if="loading">购物车加载中...</h2>
    <h2 v-else>商品列表：购物车(总类{{ typeCount }} 数量{{ count }})</h2>
    <ul>
      <li class="product" v-for="item in productList" :key="'product-'+item.id">
        <span class="product-title">{{ item.title }}</span>
        <button @click="reduce(item)">-</button>
        <span>{{ item.number }}</span>
        <button @click="add(item)">+</button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { Product, CartModule } from '@/store/modules/cart'

@Component({
  name: 'ProductList',
})
export default class extends Vue {
  productList: Product[] = [
    {
      id: 1,
      title: '电脑',
      number: 0,
    },
    {
      id: 2,
      title: '手机',
      number: 0,
    },
    {
      id: 3,
      title: '键盘',
      number: 0,
    },
    {
      id: 4,
      title: '鼠标',
      number: 0,
    },
    {
      id: 5,
      title: '显示器',
      number: 0,
    },
  ]

  loading = true

  mounted() {
    this.getCartList()
  }

  get cartList() {
    return CartModule.cartList
  }

  get typeCount() {
    return CartModule.typeCount
  }

  get count() {
    return CartModule.count
  }

  // 监听购物车数量的改变
  @Watch('count', { immediate: true })
  cartListChange() {
    this.productList.forEach((product) => {
      const findCartProduct = this.cartList.find(item => item.id === product.id)
      if (findCartProduct && findCartProduct.number >= 1) {
        product.number = findCartProduct.number
      } else {
        product.number = 0
      }
    })
  }

  // 加载购物车
  getCartList() {
    this.loading = true
    CartModule.getCartList().then(() => {
      this.loading = false
    })
  }

  // 添加购物车
  add(product: Product) {
    CartModule.AddCartList(product)
  }

  // 删除购物车
  reduce(product: Product) {
    CartModule.ReduceCartList(product)
  }
}
</script>

<style lang="scss">
.product {
  .product-title {
    margin-right: 10px;
  }
}
</style>
